import java.beans.*
import java.io.*

/**
	The Book Manager manages all the books.
	1.Save the book to the XML File.
	2.Read the XML to get the Book Object.
	3.Update the infomation of the book.
	4.Get the List of all the books.
   @author Goodtiger
  */
class BookManager {

	public static final String FOLDER = "books"
	
	private BookManager(args){
		File f = new File(FOLDER)
		if(!f.exists()){
			f.mkdir();
		} 	
	}
    private static BookManager instance
    static BookManager getInstance(args) { 
		if(!instance) instance = new BookManager(args)
          return instance
    }

	/**
		Save the Book Object to the XML File.
		@param book The Book Object
		@return boolean wether the save action is successful
	*/
	boolean saveBook(book){
		try{
			def encoder = new XMLEncoder(
			new BufferedOutputStream(
			new FileOutputStream(FOLDER+File.separator+book.name+".xml")))
			encoder.writeObject(book)
			encoder.close()
			return true
		}catch(Exception e){
			println e
		return false}
	}
	/**
		Get the Book with the given name.
		@param name the name of the book to be read.
		@return book the book of the given name,but null for no such book.
	 */
	def getBook(name){
		try{
			def d = new XMLDecoder(
			new BufferedInputStream(
			new FileInputStream(FOLDER+File.separator+name+".xml")))
	   		Object result = d.readObject()
	   		d.close()
			return (Book) result
		}catch(Exception e){return null}
	}
	/**
		Get all the books in ths folders.
		@return all the books
	*/
	def getAllBooks(){
		def list = new LinkedList<Book>()
		def folder = new File(FOLDER)
		if(folder.exists()&&folder.isDirectory()){
			def files = folder.listFiles();
			for(file in files){
				def name = file.getName()
				if(!name.endsWith('.xml')){
					continue
				}else{
				def bookName = name.substring(0,name.lastIndexOf('.'))
				list.add(getBook(bookName))
				}
			}
		}
		return list
	}
}